package org.example.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.example.protocol.RpcRequest;
import org.example.protocol.RpcResponse;

import java.util.concurrent.Callable;

public class RpcResponseHandler extends SimpleChannelInboundHandler<RpcResponse> implements Callable {

    private RpcRequest rpcRequest;

    private RpcResponse rpcResponse;

    private ChannelHandlerContext channelHandlerContext;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        this.channelHandlerContext = ctx;
    }

    @Override
    protected synchronized void channelRead0(ChannelHandlerContext ctx, RpcResponse msg) throws Exception {
        this.rpcResponse = msg;
        notify();
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        ctx.channel().close();
    }

    @Override
    public synchronized Object call() throws InterruptedException {
        channelHandlerContext.channel().writeAndFlush(this.rpcRequest);
        wait(150);
        return this.rpcResponse;
    }

    public void setRpcRequest(RpcRequest rpcRequest) {
        this.rpcRequest = rpcRequest;
    }

    public void setRpcResponse(RpcResponse rpcResponse) {
        this.rpcResponse = rpcResponse;
    }
}
